package com.android.bonn.fast.widget.view.recyclerview;

import android.view.View;
import android.view.ViewGroup;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.recyclerview.widget.RecyclerView;

public class EmptyStateRecyclerViewHelper implements LifecycleObserver {

    private View emptyView;
    private RecyclerView recyclerView;
    private final RecyclerView.Adapter adapter;

    private RecyclerView.AdapterDataObserver observer = new RecyclerView.AdapterDataObserver() {
        @Override
        public void onChanged() {
            super.onChanged();
            if (adapter.getItemCount() > 0) {
                recyclerView.setVisibility(View.VISIBLE);
                emptyView.setVisibility(View.GONE);
            } else {
                recyclerView.setVisibility(View.GONE);
                emptyView.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            super.onItemRangeInserted(positionStart, itemCount);
            if (adapter.getItemCount() > 0) {
                recyclerView.setVisibility(View.VISIBLE);
                emptyView.setVisibility(View.GONE);
            } else {
                recyclerView.setVisibility(View.GONE);
                emptyView.setVisibility(View.VISIBLE);
            }
        }
    };

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy() {
        if (adapter != null) {
            adapter.unregisterAdapterDataObserver(observer);
        }
    }


    private EmptyStateRecyclerViewHelper(Builder builder) {
        emptyView = builder.emptyView;
        recyclerView = builder.recyclerView;
        adapter = recyclerView.getAdapter();
        bindView();
    }


    private void bindView() {

        if (recyclerView.getParent() instanceof ViewGroup && emptyView != null) {
            ((ViewGroup) recyclerView.getParent()).addView(emptyView, recyclerView.getLayoutParams());
        }

        if (adapter != null) {
            adapter.registerAdapterDataObserver(observer);
            observer.onChanged();
        } else {
            throw new RuntimeException("This RecyclerView has no adapter, you must call setAdapter first!");
        }

    }


    public static final class Builder {
        private View emptyView;
        private RecyclerView recyclerView;

        public Builder() {
        }

        public Builder emptyView(View emptyView) {
            this.emptyView = emptyView;
            return this;
        }

        public Builder recyclerView(RecyclerView recyclerView) {
            this.recyclerView = recyclerView;

            return this;
        }

        public EmptyStateRecyclerViewHelper build() {
            return new EmptyStateRecyclerViewHelper(this);
        }

    }
}
